//
//  LXDRadioViewController.m
//  BLDMusics
//
//  Created by lxd on 16/3/18.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "LXDRadioViewController.h"

@interface LXDRadioViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

/**底部collection*/
@property (nonatomic, retain) UICollectionView *collection;

/**源数据数组*/
@property (nonatomic, retain) NSMutableArray *modelArr;

/**动态加载图下面的view*/
@property (nonatomic, retain) UIView *hudView;

/**判断是否播放状态*/
@property (nonatomic, assign) BOOL isPlay;

/**点击item时的歌曲数据*/
@property (nonatomic, retain) NSMutableArray *songArray;

/**从播放列表取歌曲的下表*/
@property (nonatomic, assign) NSInteger count;

/**让歌曲连续播放的定时器*/
@property (nonatomic, retain) NSTimer *timer;

/**下一曲的播放器*/
@property (nonatomic, retain) NSTimer *nextTimer;

/**存储当前播放歌曲的item的下标*/
@property (nonatomic, retain) NSIndexPath *index;

@end

@implementation LXDRadioViewController

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"电台";
    [self createCollection];
    [self dataHandle];
    
    
}

#pragma mark - 创建collection
- (void)createCollection {
    self.modelArr = [NSMutableArray array];
    self.songArray = [NSMutableArray array];
    _isPlay = NO;
    _count = 0;
    
    // collection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 30) / 2, (SCREEN_WIDTH - 30) / 4);
    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 30);
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64) collectionViewLayout:layout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collection];
    // 注册
    [self.collection registerClass:[LXDRadioCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collection registerClass:[LXDRadioCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    // 加载菊花的视图
    self.hudView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    _hudView.center = CGPointMake(self.view.center.x, _collection.frame.size.height / 2);
    [self.view addSubview:_hudView];
    
 
}


#pragma mark - collection的协议方法
#pragma mark  分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _modelArr.count;
}
#pragma mark 每个分区的item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    LXDRadioModel *model = _modelArr[section];
    return model.data.count;
}
#pragma mark 返回item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LXDRadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    // 先取出分区
    LXDRadioModel *model = _modelArr[indexPath.section];
    // 再取出分区里的小model
    LXDRadioModel *modelTwo = model.data[indexPath.row];
    cell.model = modelTwo;

    // 先将所有的播放按钮都默认为未播放状态
    [cell.playButton setImage:PLAY forState:UIControlStateNormal];
    // 播放器正在播放
    if ([AVPlayerManger shareplayer].isPlaying == YES) {
        if (indexPath.row == [AVPlayerManger shareplayer].row && indexPath.section == [AVPlayerManger shareplayer].section) {
            [cell.playButton setImage:PAUSE forState:UIControlStateNormal];
        }
    } else {
         [cell.playButton setImage:PLAY forState:UIControlStateNormal];
    }
    
    return cell;
}
#pragma mark 返回分区头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        LXDRadioCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.model = _modelArr[indexPath.section];
        return header;
    }
    return nil;
}
#pragma mark 点击item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 取出网址
    LXDRadioModel *model = _modelArr[indexPath.section];
    LXDRadioModel *modelTwo = model.data[indexPath.row];
    
    
    //获取当前点击的cell
    LXDRadioCollectionViewCell *cell = (LXDRadioCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
   
    // 点击正在播放的歌曲
    if ([AVPlayerManger shareplayer].isPlaying == YES) {
        // 如果点击的是当前正在播放的，那就暂停
        if (indexPath.row == [AVPlayerManger shareplayer].row && indexPath.section == [AVPlayerManger shareplayer].section) {
            [cell.playButton setImage:PLAY forState:UIControlStateNormal];
            [[AVPlayerManger shareplayer] pause];
        } else {
            // 如果点击的和当前正在播放的不是同一个，则暂停上一个,播放这一个
            LXDRadioCollectionViewCell *cell1 = (LXDRadioCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:[AVPlayerManger shareplayer].row inSection:[AVPlayerManger shareplayer].section]];
            [cell1.playButton setImage:PLAY forState:UIControlStateNormal];
            [cell.playButton setImage:PAUSE forState:UIControlStateNormal];
            [AVPlayerManger shareplayer].row = indexPath.row;
            [AVPlayerManger shareplayer].section = indexPath.section;
            [self radioHandle:modelTwo];

        }
    } else {
        [cell.playButton setImage:PAUSE forState:UIControlStateNormal];
        [AVPlayerManger shareplayer].row = indexPath.row;
        [AVPlayerManger shareplayer].section = indexPath.section;
        [self radioHandle:modelTwo];
    }
    
}
#pragma mark - 点击结束的时候(点击下一个的时候)
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

    // 将上一个的歌曲停止播放
    LXDRadioCollectionViewCell *cell = (LXDRadioCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [[AVPlayerManger shareplayer] pause];
    [cell.playButton setImage:PLAY forState:UIControlStateNormal];
    _count = 0;
}


#pragma mark - 数据处理
- (void)dataHandle {
    [MBProgressHUD showHUDAddedTo:_hudView animated:YES];
    [APPTools GETWithURL:@"http://api.fm.ttpod.com/radio?" par:nil success:^(id responseObject) {
        self.modelArr = [LXDRadioModel modelHandleWithArray:responseObject[@"data"]];
        [_collection reloadData];
        [MBProgressHUD hideHUDForView:_hudView animated:YES];
        [_hudView removeFromSuperview];
    } filed:^(NSError *error) {
        
    }];
}
#pragma mark 点击item放歌的数据处理
- (void)radioHandle:(LXDRadioModel *)model {
   
    NSString *str = [NSString stringWithFormat:@"http://api.fm.ttpod.com/radiosong?num=150&tagid=%@", model.tag_id];
    
    [APPTools GETWithURL:str par:nil success:^(id responseObject) {
        self.songArray = [LXDPlayRadioModel modelHandleWithArray:responseObject[@"data"]];
        // 播放
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(playMusic) userInfo:nil repeats:NO];
        
    } filed:^(NSError *error) {
        
    }];
    
}


- (void)playMusic {
    
    // 失效
    [_timer invalidate];
    // 如果歌曲总数大于当前播放的音乐下标
    if (_count < _songArray.count) {
        LXDPlayRadioModel *model = [_songArray objectAtIndex:_count];
        
        [[AVPlayerManger shareplayer] playWithUrl:model.url];
        
        // 播放进度监听
        [[AVPlayerManger shareplayer].audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            
            CGFloat duration = CMTimeGetSeconds([AVPlayerManger shareplayer].audioPlayer.currentItem.duration)
            ;
            CGFloat current = CMTimeGetSeconds([AVPlayerManger shareplayer].audioPlayer.currentItem.currentTime);
            
            NSLog(@"%f %f", duration, current);
            if (duration == NAN) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"因为受版权限制" message:@"已经为您过滤" preferredStyle:UIAlertControllerStyleActionSheet];
                [self presentViewController:alert animated:YES completion:nil];
                [self dismissViewControllerAnimated:alert completion:nil];
            }
            if (duration == current) {
                self.nextTimer =  [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(nextSongList) userInfo:nil repeats:NO];
            }
        }];

    }

}


- (void)nextSongList {
    _count++;
    // 当播放到最后一首歌时，播放器停止，按钮暂停
    _nextTimer = nil;
    if (_count == _songArray.count) {
        NSIndexPath *index = [NSIndexPath indexPathForRow:[AVPlayerManger shareplayer].row inSection:[AVPlayerManger shareplayer].section];
        LXDRadioCollectionViewCell *cell = (LXDRadioCollectionViewCell *)[_collection cellForItemAtIndexPath:index];
        [[AVPlayerManger shareplayer] pause];
        [cell.playButton setImage:PLAY forState:UIControlStateNormal];
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(playMusic) userInfo:nil repeats:NO];
 
}



- (void)viewWillDisappear:(BOOL)animated {
    
    [PlayViewController sharePlayViewBar].hidden = NO;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
